/*
 * Copyright (c) 2012 Acorn International.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http:www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.chinadrtv.batch.admin.jobs.ozing.paid;

import com.chinadrtv.batch.admin.service.OzingCardBatchService;
import com.chinadrtv.user.service.ozing.OzingCardService;
import com.chinadrtv.user.model.CardType;
import com.chinadrtv.user.model.OzingCard;
import com.chinadrtv.user.model.OzingCardBatch;
import com.chinadrtv.user.util.CardUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * User: Jack.Chen
 * Date: 12-12-17
 */

public class PaidCardItemReader implements ItemReader<OzingCard> {
    private static Log log = LogFactory.getLog(PaidCardItemReader.class);


    final SimpleDateFormat sf = new SimpleDateFormat("yyMMdd");

    private int counter = 0;
    private int cardIndex = 0;

    //Job parameters
    private long quantity;
    private long cardValue;
    private long cardSalePrice;
    private String periodType;
    private long period;
    private Date deadline;
    private String cardType;
    private Long batchId;
    private OzingCardBatch batch;

    @Autowired
    private OzingCardService ozingCardService;

    @Autowired
    private OzingCardBatchService ozingCardBatchService;


    public OzingCard read() throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("******start to run paid card job: reader******");
        }

        counter++;
        if (counter > quantity) return null; //stop job

        this.setCardIndex((cardIndex == 0 ? ozingCardService.getTodayCardIndex() : cardIndex) + 1);
        if(cardIndex>99999){
            return null;
        }

        Date today = new Date();
        String password = CardUtil.generateCardPassword(today);
        int i=0;
        while (ozingCardService.existsPassword(password) && i<100) {
            password = CardUtil.generateCardPassword(today);
            i++;
        }

        this.setBatch(batch == null ? ozingCardBatchService.get(batchId) : batch);

        String today_s = sf.format(today);

        //生成卡号:6位生产日期+5位为序列号+1位卡类别（0-活动卡，1-销售卡，2-定制卡+4位有效期
        String cardIndex_ = ("00000" + cardIndex).substring(String.valueOf(cardIndex).length());
        String period_ = ("000" + period).substring(String.valueOf(period).length());
        String cardId = today_s + cardIndex_ + period_ + periodType;

        OzingCard ozingCard = new OzingCard();
        ozingCard.setActive(false);
        ozingCard.setCardActivationDeadline(deadline);
        ozingCard.setCardId(cardId);

        ozingCard.setCardPassword(password);
        ozingCard.setCardIndex(cardIndex);
        ozingCard.setCardParValue(cardValue);
        ozingCard.setCardSalePrice(cardSalePrice);
        ozingCard.setCardType(CardType.valueOf(cardType.toUpperCase()));
        ozingCard.setCardStatus(OzingCard.CardStatus.NOT_DELIVERED);
        ozingCard.setCardValidityPeriod((int) period);
        ozingCard.setCardValidityPeriodType(OzingCard.CardPeriodType.valueOf(periodType));
        ozingCard.setDateAdded(today);
        ozingCard.setBatch(batch);

        return ozingCard;
    }


    public int getCounter() {
        return counter;
    }


    public void addCounter() {
        this.counter++;
    }

    public long getQuantity() {
        return quantity;
    }

    @Value("#{jobParameters['quantity']}")
    public void setQuantity(long quantity) {
        this.quantity = quantity;
    }

    public long getCardValue() {
        return cardValue;
    }

    @Value("#{jobParameters['cardSalePrice']}")
    public long getCardSalePrice() {
        return cardSalePrice;
    }

    public void setCardSalePrice(long cardSalePrice) {
        this.cardSalePrice = cardSalePrice;
    }

    @Value("#{jobParameters['cardValue']}")
    public void setCardValue(long cardValue) {
        this.cardValue = cardValue;
    }

    public String getPeriodType() {
        return periodType;
    }

    @Value("#{jobParameters['periodType']}")
    public void setPeriodType(String periodType) {
        this.periodType = periodType;
    }

    public long getPeriod() {
        return period;
    }

    @Value("#{jobParameters['period']}")
    public void setPeriod(long period) {
        this.period = period;
    }

    public Date getDeadline() {
        return deadline;
    }

    @Value("#{jobParameters['deadline']}")
    public void setDeadline(Date deadline) {
        this.deadline = deadline;
    }

    public String getCardType() {
        return cardType;
    }

    @Value("#{jobParameters['cardType']}")
    public void setCardType(String cardType) {
        this.cardType = cardType;
    }

    public int getCardIndex() {
        return cardIndex;
    }

    public void setCardIndex(int cardIndex) {
        this.cardIndex = cardIndex;
    }

    public Long getBatchId() {
        return batchId;
    }

    public void setBatchId(Long batchId) {
        this.batchId = batchId;
    }

    public OzingCardBatch getBatch() {
        return batch;
    }

    public void setBatch(OzingCardBatch batch) {
        this.batch = batch;
    }

}
